在單一元件檔(.vue)裡面使用 Teleport


Posted by Calon on 2022-04-30

假設今天有個 .vue 檔並且裡面有掛載一個名為 Modal 的元件:

<template>
  <div class="container">
    <header></header>
    <Modal></Modal>
  </div>
</template>

<script>
export default {
  components: {
    Modal,
  },
};
</script>
<template>
  <button type="button">開啟 Modal</button>
  <div class="modal"></div>
</template>

開起 Modal 的 button 因為跟 Modal 有關,所以將它放在 Modal 元件裡面,但我想要將這顆 button 放到父層元件的我想要放的位置,所以使用了 Teleport

<template>
  <div class="container">
    <header></header>
    <Modal></Modal>
  </div>
</template>

<script>
export default {
  components: {
    Modal,
  },
};
</script>
<template>
  <Teleport to="header">
    <button type="button">開啟 Modal</button>
  </Teleport>
  <div class="modal"></div>
</template>

但畫面並沒有正確呈現,並且在 Console 跳出了以下警語:

[Vue warn]: Failed to locate Teleport target with selector "header". 
Note the target element must exist before the component is 
mounted - i.e. the target cannot be rendered by the component itself,
and ideally should be outside of the entire Vue component tree.
[Vue warn]: Invalid Teleport target on mount: null (object)

這可能是因為在 Modal 元件掛載時父層元素並沒有掛載完成,所以導致找不到 HTML 元素。

解決方法:
使用 v-if 來判斷確定父層掛載完後再啟用 Modal 元件:

<template>
  <div class="container">
    <header></header>
    <Modal v-if="isMounted"></Modal>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isMounted: false,
    };
  },
  components: {
    Modal,
  },
  mounted() {
    this.isMounted = true;
  },
};
</script>

#Vue.js







Related Posts

How to Set Up Firewall with UFW on Ubuntu 20.04

How to Set Up Firewall with UFW on Ubuntu 20.04

Markov Decision Process 的程式範例

Markov Decision Process 的程式範例

Day01 Transfer Learning 遷移式學習

Day01 Transfer Learning 遷移式學習


Comments